﻿using System;
using System.IO;
using System.Linq;
using System.Reflection;

namespace Heroius.Cert
{
    public class Utility
    {
        /// <summary>
        /// 转换相对于入口程序集的相对地址为绝对地址
        /// </summary>
        /// <param name="relativePath">相对地址</param>
        /// <returns></returns>
        public static string GetAbsolutePath(string relativePath)
        {
            return string.Format("{0}\\{1}", Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), relativePath);
        }

        /// <summary>
        /// 尝试加载指定位置的程序集，若在当前应用程序域的已加载程序集中找到同名程序集，则返回该已加载程序集而不再尝试加载
        /// </summary>
        /// <param name="AssemblyPath"></param>
        /// <returns></returns>
        public static Assembly TryLoadAssembly(string AssemblyPath)
        {
            var name = Path.GetFileNameWithoutExtension(AssemblyPath);
            var asms = AppDomain.CurrentDomain.GetAssemblies();
            var already = asms.Select(asm => asm.GetName().Name);
            if (already.Contains(name))
                return asms.First(asm => asm.GetName().Name == name);
            else
            {
                if (File.Exists(AssemblyPath)) return Assembly.LoadFrom(AssemblyPath); //note 此处必须使用LoadFrom，若使用LoadFile则不会同时加载默认的依赖项
                else return Assembly.Load(name);
            }
        }
    }
}
